<?php
/**
 * Created by PhpStorm.
 * User: majiawen
 * Date: 2018/1/30
 * Time: 10:11
 */

namespace app\common\Server;

use app\common\Service;
use think\Config;

class AdminCaptcha extends Service
{

    private $redis = null;
    private $config = null;

    //有效时间（10分钟）
    const EXPIRE = 600;

    //键名
    const PREFIX = 'CACHE:ADMINCAPTCAH:%s';

    //发送时间隔限制
    const INTERVAL = 'CACHE:ADMINCAPTCAH:LOCKED:%s';

    //当天发送次数
    const COUNTS   = 'CACHE:ADMINCAPTCAH:COUNT:%s:%s';	// 手机号 - 日期

    public function __construct()
    {
        $redis = new Redis();
        $this->redis = $redis->handler();
        $this->config = Config::get('captcha');
//        $this->redis = Redis::getInstance();
    }

    /**
     * 发送验证码
     * @param $mobile
     * @param int $sms_type
     * @return bool|int
     */
    public function send($mobile, $sms_type = 0)
    {
        $res = $this->check($mobile);
        if(!$res){
            return self::$data;
        }
        $code = $this->set($mobile);
        $rtn = Sms::instance()->sendCaptch($mobile, $code, $sms_type);

        if($rtn){
            return true;
        }
        return false;
    }

    /**
     * 检查是否允许发送验证码
     * @param $mobile
     * @return bool|int
     */
    public function check($mobile)
    {
        $redis = $this->redis;
        //是否在重复发布限制内
        $mkey  = sprintf(self::INTERVAL, $mobile);
        if ($redis->exists($mkey)){
            self::$data = 2;
            return false;
        }

        //是否超出当日发送限制
        $nkey = sprintf(self::COUNTS, $mobile, date('Ymd'));
        $numb = intval($redis->get($nkey));
        if ($numb > $this->config['daylimit']){
            self::$data = 3;
            return false;
        }

        return true;
    }

    /**
     * 设置验证码
     * @param $mobile
     * @return int
     */
    public function set($mobile)
    {
        $redis = $this->redis;

        $code  = rand(100000, 999999);
        $ckey  = sprintf(self::PREFIX, $mobile);
        $redis->setex($ckey, self::EXPIRE, $code);

        //设置两次间隔
        $mkey  = sprintf(self::INTERVAL, $mobile);
        $redis->setex($mkey, $this->config['interval'], time());

        //每天请求次数递增
        $nkey = sprintf(self::COUNTS, $mobile, date('Ymd'));
        $redis->incr($nkey);
        $redis->expire($nkey, 86400);

        return $code;
    }

    /*
     * 判断验证码是否正确
     * @param $mobile
     * @return bool
     * */
    public function verify($mobile,$captcha){
        //验证验证码
        $redis = $this->redis;
        $ckey  = sprintf(self::PREFIX, $mobile);

        $redis_captcha = $redis->get($ckey);
        if($redis_captcha != $captcha){
            return false;
        }
        return true;
    }
}